var express = require('express');
var fs = require('fs');
var resumable = require('./resumable-node.js')('/tmp/resumable.js/');
var app = express();
var multipart = require('connect-multiparty');
var crypto = require('crypto');

// 将大多数内容托管在公用文件夹中
app.use(express.static(__dirname + '/public'));

app.use(multipart());

// 取消注释以允许CORS
app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header("Access-Control-Allow-Headers","content-type");
  res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
  next();
});

// 检索文件ID。使用/fileid?filename=my-file.jpg调用
app.get('/fileid', function(req, res){
  if(!req.query.filename){
    return res.status(500).end('查询参数丢失');
  }
  // 从文件名创建md5哈希
  res.end(
    crypto.createHash('md5')
    .update(req.query.filename)
    .digest('hex')
  );
});



const files = {}
function mergeFile(files) {
  const filePath = './'+files[1].name
  const fileWriteStream = fs.createWriteStream(filePath)
  for(let key in files) {
    const chunkpath = files[key].path
    // console.log('开始合并第'+key+'个')
    // 读取切片数据
    const data = fs.readFileSync(chunkpath)
    // 将切片追加到存储文件
    fs.appendFileSync(filePath, data)
    // 删除切片文件
    fs.unlinkSync(chunkpath)
  }
  fileWriteStream.close()
}


// 通过Resumable.js处理上传
app.post('/upload', function(req, res){
    resumable.post(req, function(status, filename, original_filename, identifier){
        // console.log('POST', status, original_filename, identifier);
        const reqData = req.body
        if(!files[reqData.resumableIdentifier]) files[reqData.resumableIdentifier] = {}
        files[reqData.resumableIdentifier][reqData.resumableChunkNumber] = req.files.file
        // console.log(req.files.file)

        if(+reqData.resumableTotalChunks === Object.keys(files[reqData.resumableIdentifier]).length) {
          console.log('上传完成，开始合并')
          mergeFile(files[reqData.resumableIdentifier])
          files[reqData.resumableIdentifier] = {}
          console.log('合并完成')
        }
        res.send(status);
    });
});

// 通过Resumable.js处理块的状态检查
app.get('/upload', function(req, res){
    resumable.get(req, function(status, filename, original_filename, identifier){
        console.log('GET', status);
        res.send((status == 'found' ? 200 : 404), status);
    });
});

app.get('/download/:identifier', function(req, res){
	resumable.write(req.params.identifier, res);
});
app.get('/resumable.js', function (req, res) {
  var fs = require('fs');
  res.setHeader("content-type", "application/javascript");
  fs.createReadStream("../../resumable.js").pipe(res);
});

app.listen(3000);
